package com.ai.aicontact.busi.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.aicontact.busi.entity.ChannelDef;
import com.ai.aicontact.busi.service.ChannelDefService;
import com.ai.aicontact.common.cache.AppCacheManager;
import com.ai.aicontact.common.constant.GlobalConstant;
import com.ai.aicontact.core.dao.BaseDaoI;

@Service
public class ChannelDefServiceImpl implements ChannelDefService {
	private AppCacheManager appCacheManager = AppCacheManager.getInstance();
	private Map m_cache_by_key_code = null;

	@Autowired
	private BaseDaoI<ChannelDef> channelDefDao;
 
	public ChannelDefServiceImpl() {
		if (m_cache_by_key_code == null)
			m_cache_by_key_code = appCacheManager.getMap(GlobalConstant.CACHE_BY_KEY_CODE);
	}

	public void refreshCache() throws Exception {
		m_cache_by_key_code.remove(GlobalConstant.CACHE_KEY_CHANNEL_DEF);
		List<ChannelDef> channelDefs =  getAllChannelDef();
		m_cache_by_key_code.put(GlobalConstant.CACHE_KEY_CHANNEL_DEF, channelDefs);
	}
	
	 
 
	private List<ChannelDef> getAllChannelDef() throws Exception {
		String hql = "from ChannelDef where state = 1";
		List<ChannelDef> channelDefList = channelDefDao.find(hql);
		return channelDefList;
	}


	@Override
	public List<ChannelDef> getChannelDef() throws Exception {
		if(!m_cache_by_key_code.containsKey(GlobalConstant.CACHE_KEY_CHANNEL_DEF)){
			List<ChannelDef> channelDefs =  getAllChannelDef();
			m_cache_by_key_code.put(GlobalConstant.CACHE_KEY_CHANNEL_DEF, channelDefs);
		} 
		List<ChannelDef> channelDefList = (List<ChannelDef>)m_cache_by_key_code.get(GlobalConstant.CACHE_KEY_CHANNEL_DEF);
		return channelDefList;
	}

	@Override
	public ChannelDef getChannelDefByChannelId(Long channelId) throws Exception {
		String hql = "from ChannelDef where state=1 AND channelId = :channelId";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("channelId", channelId);
		ChannelDef channelDef = channelDefDao.get(hql, params);
		return channelDef;
	}

  
	
}
